<template>
  <el-row>
    <el-card>
      <el-row>
        <span style="line-height: 33px">
          {{ $t('collectionWorkbench.dataInfo') }}
        </span>
        <el-badge :is-dot="msgDot" class="item">
          <el-button icon="el-icon-message" circle type="primary" size="small" @click="msgView" />
        </el-badge>
      </el-row>
      <el-divider />
      <el-row v-loading="reportLoading" :gutter="10">
        <el-col :span="8">
          <!-- 催回案件数 -->
          <div class="dataSection">
            <span> {{ pushBackOrderTotalNum }} </span>
            <span> {{ $t('collectionWorkbench.finishCaseCount') }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <!-- 今日催回案件数/已分配催收案件总数 -->
          <div class="dataSection">
            <span> {{ todayPushBackOrderNum }} / {{ allotOrderTotalNum }} </span>
            <span> {{ $t('collectionWorkbench.todayFinishCaseCount') }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <!-- 同阶段同组排名 -->
          <div class="dataSection">
            <span> {{ groupRanking }} </span>
            <span> {{ $t('collectionWorkbench.groupRanking') }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <!-- 催回案件金额 -->
          <div class="dataSection">
            <span> {{ pushBackOrderTotalMoney }} </span>
            <span> {{ $t('collectionWorkbench.finishCaseAmount') }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <!-- 今日催回案件金额/今日催回案件应还总额 -->
          <div class="dataSection">
            <span> {{ todayPushBackMoney }} / {{ todayPushBackTotalMoney }} </span>
            <span> {{ $t('collectionWorkbench.todayFinishCaseAmount') }} </span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="dataSection">
            <span> {{ stageRanking }}</span>
            <span> {{ $t('collectionWorkbench.stageRanking') }} </span>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <el-button-group>
        <el-button
          :type="chType === 1 ? 'primary' : ''"
          @click="changeStatus(1)"
        >
          {{ $t('collectionWorkbench.list') }}
        </el-button>
        <el-button
          :type="chType === 2 ? 'primary' : ''"
          @click="changeStatus(2)"
        >
          {{ $t('collectionWorkbench.retainedCase') }}
        </el-button>
        <el-button
          :type="chType === 3 ? 'primary' : ''"
          @click="changeStatus(3)"
        >
          {{ $t('collectionWorkbench.successfulCase') }}
        </el-button>
      </el-button-group>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item :label="$t('collectionManagement.amountBreakdown.recallDate')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.days')">
          <el-input
            v-model="searchForm.dueDays"
            :controls="false"
            :max="10000000000000"
            :placeholder="$t('collectionManagement.caseManagement.prompt.days')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item v-if="!exHidden" :label="$t('collectionManagement.caseManagement.searchModel.stage')">
          <el-select v-model="searchForm.stageId" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.stage')">
            <el-option
              v-for="item in allStage"
              :key="item.id"
              :label="item.phaseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.reminderTime')">
          <el-date-picker
            v-model="remindTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.orderType')">
          <el-select v-model="searchForm.orderType" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.orderType')">
            <el-option
              v-for="item in $t('collectionManagement.caseManagement.orderType')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.orderNo')">
          <el-input
            v-model="searchForm.orderNo"
            clearable
            :maxlength="50"
            :placeholder="$t('collectionManagement.caseManagement.prompt.orderNo')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.phoneNumber')">
          <el-input
            v-model="searchForm.phonenum"
            clearable
            :maxlength="50"
            :placeholder="$t('collectionManagement.caseManagement.prompt.phoneNumber')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.name')">
          <el-input
            v-model="searchForm.username"
            clearable
            :maxlength="50"
            :placeholder="$t('collectionManagement.caseManagement.prompt.name')"
          />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%;"
        @sort-change="changeSort"
      >
        <el-table-column
          fixed="left"
          prop="creditOrderNo"
          :label="tableText['letterReview']"
          min-width="170"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="auth(scope.row)">
              {{ scope.row.creditOrderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          fixed="left"
          prop="orderNo"
          :label="tableText['orderNo']"
          min-width="170"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row)">
              {{ scope.row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="staffName"
          :label="tableText['recruiter']"
          min-width="200"
        />
        <el-table-column
          prop="collectionLogRemark"
          :label="tableText['collectionLog']"
          min-width="150"
        />
        <el-table-column
          prop="collectionLogTime"
          :label="tableText['updateTime']"
          min-width="150"
        />
        <el-table-column
          prop="remindTime"
          :label="tableText['reminderTime']"
          min-width="150"
        />
        <el-table-column
          prop="keep"
          :label="tableText['retain']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ $t('collectionManagement.caseManagement.keep')[scope.row['keep']] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderCreateTime"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          prop="userPhone"
          :label="tableText['userNo']"
          min-width="150"
        />
        <el-table-column
          prop="userName"
          :label="tableText['userName']"
          min-width="200"
        />
        <el-table-column
          prop="orderType"
          :label="tableText['productType']"
          min-width="250"
        >
          <template slot-scope="scope">
            {{ setType(scope.row['orderType']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="applyMoney"
          :label="tableText['applyCash']"
          min-width="120"
        />
        <el-table-column
          prop="loanDays"
          :label="tableText['limit']"
          min-width="120"
        >
          <template slot-scope="scope">
            <p v-if="scope.row['loanDays'] && scope.row['loanMonths']">
              {{ scope.row['loanDays'] * scope.row['loanMonths'] }} {{ $t('collectionManagement.caseManagement.day') }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="currentPeriod"
          :label="tableText['period']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row['currentPeriod'] }} / {{ scope.row['totalPeriod'] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realRepay"
          :label="tableText['repayMoneyShould']"
          min-width="170"
        />
        <el-table-column
          prop="applyMoney"
          :label="tableText['principal']"
          min-width="150"
        />
        <el-table-column
          prop="interestMoney"
          :label="tableText['interest']"
          min-width="120"
        />
        <el-table-column
          prop="serviceCharge"
          :label="tableText['serviceFee']"
          min-width="190"
        />
        <el-table-column
          prop="overDueFine"
          :label="tableText['overdueFee']"
          min-width="150"
        />
        <el-table-column
          prop="planRepaymentDate"
          :label="tableText['RepayTimeShould']"
          min-width="170"
        />
        <el-table-column
          prop="dueDays"
          :label="tableText['dueDay']"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['dueDays'] }} {{ $t('collectionManagement.caseManagement.day') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realRepayMoney"
          :label="tableText['realRepayMoney']"
          min-width="120"
        />
        <el-table-column
          prop="realRepaymentDate"
          :label="tableText['repaymentDate']"
          min-width="120"
        />
        <el-table-column
          prop="currentRepay"
          :label="tableText['amountDue']"
          min-width="120"
        />
        <el-table-column
          fixed="right"
          prop="orderStatus"
          :label="tableText['orderStatus']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ $t('collectionManagement.caseManagement.stats')[scope.row['orderStatus']] }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="150"
        >
          <template slot-scope="scope">
            <el-row v-if="scope.row['orderStatus'] === 11 || scope.row['orderStatus'] === 5 || scope.row['orderStatus'] === 3 || scope.row['orderStatus'] === 1">
              <el-button v-if="scope.row['keep'] === 2" size="small" @click="retain(scope.row['id'], 1)">{{ $t('collectionManagement.caseManagement.retain') }}</el-button>
              <el-button v-if="scope.row['keep'] === 1" size="small" @click="retain(scope.row['id'], 2)">
                {{ $t('collectionManagement.caseManagement.cancelRetain') }}
                <span style="padding-left: 5px">
                  {{ scope.row['remainDays'] }}{{ $t('collectionManagement.caseManagement.day') }}
                </span>
              </el-button>
            </el-row>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <msg-dialog
      :msg-show="msgShow"
      :msg-data="msgData"
      @change-dialog="changeDialog"
      @msg-view="msgView"
    />
  </el-row>
</template>

<script>
import { queryOverdueOrderInWorkbench, exportOverdueOrderInWorkbench, getBusinessConfig, getCurrentEmployeeStaffID, getAdminReport, setOverdueOrderKeep, getRemindList } from '@/api/collection'
import { formatDate, ObjToQueryString } from '@/utils/method'
import MsgDialog from '@/components/collection/msg-dialog'
export default {
  name: 'CollectionWorkbench',
  components: {
    MsgDialog
  },
  data() {
    return {
      pushBackOrderTotalNum: 0,
      todayPushBackOrderNum: 0,
      allotOrderTotalNum: 0,
      groupRanking: 0,
      pushBackOrderTotalMoney: 0,
      todayPushBackMoney: 0,
      todayPushBackTotalMoney: 0,
      stageRanking: 0,
      chType: 1,
      time: [],
      remindTime: [],
      allStage: [],
      exHidden: false,
      loading: true,
      reportLoading: true,
      tableText: {},
      totalNumber: 0,
      tableData: [],
      searchForm: this.params(),
      staffID: null,
      staffName: null,
      recallPhone: null,
      recallPhonePassword: null,
      ws: null,
      msgDot: false,
      userId: null,
      msgData: [],
      msgShow: false
    }
  },
  mounted() {
    this.tableText = this.$t('collectionManagement.caseManagement.tabData')
    this.userId = JSON.parse(sessionStorage.getItem('loginInfo'))['id']
    this.sendWS(this.userId)
    this.getAllStage()
    this.getStaffInfo()
  },
  methods: {
    sendWS(id) {
      const url = process.env.VUE_APP_BASE_API
      const num = url.indexOf('/')
      this.ws = new WebSocket(`wss:${url.substring(num)}`)
      this.ws.onopen = (evt) => {
        console.log('WebSocket开启成功')
        this.ws.send(id)
      }
      this.ws.onmessage = (evt) => {
        console.log('收到回复数据: ' + evt.data)
        if (evt.data) {
          this.msgDot = true
        }
      }
      this.ws.onclose = (evt) => {
        console.log('WebSocket已关闭')
      }
    },
    getStaffInfo() {
      getCurrentEmployeeStaffID()
        .then(res => {
          if (res.success) {
            if (res.data) {
              this.staffID = res.data['id']
              this.staffName = res.data['staffName']
              this.recallPhone = res.data['recallPhone']
              this.recallPhonePassword = res.data['recallPhonePassword']
              this.searchModel.stageId = res.data['stageId']
              this.exHidden = true
            } else {
              this.exHidden = false
            }
            this.adminReport()
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    adminReport() {
      this.reportLoading = true
      const userId = this.staffID !== null ? this.staffID : 0
      getAdminReport(userId)
        .then(res => {
          if (res.success) {
            this.reportLoading = false
            if (res.data && res.data['staffReportVO']) {
              const data = res.data['staffReportVO']
              this.pushBackOrderTotalNum = data['pushBackOrderTotalNum']
              this.todayPushBackOrderNum = data['todayPushBackOrderNum']
              this.allotOrderTotalNum = data['allotOrderTotalNum']
              this.groupRanking = data['groupRanking']
              this.pushBackOrderTotalMoney = data['pushBackOrderTotalMoney']
              this.todayPushBackMoney = data['todayPushBackMoney']
              this.todayPushBackTotalMoney = data['todayPushBackTotalMoney']
              this.stageRanking = data['stageRanking']
            }
          } else {
            this.reportLoading = false
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.reportLoading = false
          this.$message.error(err.message)
        })
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        planRepaymentDateStart: null,
        planRepaymentDateEnd: null,
        dueDays: null,
        stageId: '',
        remindDateStart: null,
        remindDateEnd: null,
        orderType: '',
        userGrade: null,
        orderNo: null,
        phonenum: null,
        isAscend: null,
        username: null,
        columns: ['due_days'],
        orderBy: [true]
      }
    },
    reset() {
      this.searchForm = this.params()
      this.time = null
      this.reminderTime = null
      this.getData()
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    changeStatus(type) {
      this.chType = type
      this.getData()
    },
    searchData() {
      const data = {
        orderStatus: this.chType,
        dueDays: this.searchForm.dueDays,
        stageId: this.searchForm.stageId,
        staffId: this.staffID,
        type: this.chType,
        orderType: this.searchForm.orderType,
        userGrade: this.searchForm.userGrade,
        orderNo: this.searchForm.orderNo,
        phonenum: this.searchForm.phonenum,
        username: this.searchForm.username,
        isAscend: this.searchForm.isAscend,
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        columns: this.searchForm.columns,
        orderBy: this.searchForm.orderBy
      }
      if (this.time && this.time.length > 1) {
        data['planRepaymentDateStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['planRepaymentDateEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['planRepaymentDateStart'] = null
        data['planRepaymentDateEnd'] = null
      }
      if (this.reminderTime && this.remindTime.length > 1) {
        data['remindDateStart'] = formatDate(new Date(this.remindTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['remindTimeEnd'] = formatDate(new Date(this.remindTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['remindTimeStart'] = null
        data['remindTimeEnd'] = null
      }
      return data
    },
    getData() {
      this.loading = true
      const data = this.searchData()
      queryOverdueOrderInWorkbench(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    test(data) {
      let value = this[data]
      if (value.length > 0) {
        value = value.replace(/[^0-9]/g, '')
      }
      this[data] = value
    },
    getAllStage() {
      const data = {
        isPage: false
      }
      getBusinessConfig(data)
        .then(res => {
          if (res.success) {
            this.allStage = res.data.filter(item => {
              return item['state'] === 'ACTIVATE'
            })
            const obj = [{
              phaseName: this.$t('common.all'),
              id: ''
            }]
            this.allStage = obj.concat(this.allStage)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    exportList() {
      exportOverdueOrderInWorkbench(this.searchData())
    },
    changeSort(val) {
      this.searchForm.isAscend = val.order === 'ascending'
      this.search()
    },
    toDetail(item) {
      const paramData = {
        from: 'caseManagement',
        orderNo: item['orderNo'],
        userId: item['userId'],
        creditOrderId: item['creditOrderId'],
        orderStatus: item['orderStatus'],
        orderId: item['orderId'],
        staffID: item['staffID'],
        staffName: item['staffName'],
        recallPhone: this.recallPhone,
        recallPhonePassword: this.recallPhonePassword
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/collectionCenter/collectDetail?${para}`, '_blank')
    },
    auth(item) {
      const paramData = {
        from: 'orderList',
        status: item['orderStatus'],
        userId: item['userId'],
        orderId: item['creditOrderId'],
        orderNo: item['creditOrderNo']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
    },
    setType(data) {
      const name = this.$t('collectionManagement.caseManagement.orderType').filter(v => {
        return v['value'] === data
      })
      return name && name[0] && name[0]['desc'] ? name[0]['desc'] : ''
    },
    retain(id, keepFlag) {
      const data = {
        id,
        keepFlag
      }
      this.loading = true
      setOverdueOrderKeep(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    msgView() {
      getRemindList(this.userId)
        .then(res => {
          if (res.success) {
            this.msgData = res.data
            this.msgShow = true
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    changeDialog(param) {
      this.msgShow = param
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
.el-divider{
  margin: 10px 0 5px 0;
}
.item{
  margin-left: 20px;
}
.dataSection {
  width: 100%;
  text-align: center;
  height: 100px;
  background: #409EFF;
  margin: 5px 0;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
.dataSection > span:nth-of-type(1) {
  font-size: 20px;
  color: #fff;
  margin-bottom: 5px;
  font-weight: bolder;
}
.dataSection > span:nth-of-type(2) {
  color: #fff;
  font-size: 17px;
}
</style>
